﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using WebApiOrm.Domain;

namespace WebApiOrm.Provider.EFCoreSqlite
{
    /// <summary>
    /// IOrmProvider实现者
    /// </summary>
    sealed class EFCoreOrmProvider : IOrmProvider
    {
        private readonly EFCoreDbContext dbContext;

        public Version? Version => typeof(DbContext).Assembly.GetName().Version;

        public EFCoreOrmProvider(EFCoreDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public async Task<bool> AddSysUserAsync(SysUser user)
        {
            this.dbContext.SysUser.Add(user);
            var count = await this.dbContext.SaveChangesAsync();
            return count > 0;
        }

        public async Task<IList<SysUser>> QuerySysUsersAsync(Expression<Func<SysUser, bool>> predicate, int skip, int take)
        {
            return await this.dbContext.SysUser.Where(predicate).OrderBy(item => item.Id).Skip(skip).Take(take)
                .AsNoTracking()
                .ToArrayAsync();
        }
    }
}